package com.shiro.demo.shiro;

import com.shiro.demo.pojo.User;
import com.shiro.demo.service.UserService;
import com.shiro.demo.service.impl.UserServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * my realm
 * </p>
 *
 * @author liup
 * @since 2020/10/20
 */
public class MyRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("拦截进入授权方法->doGetAuthorizationInfo");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获取登录用户
        Subject subject = SecurityUtils.getSubject();
        User loginUser = (User)subject.getPrincipal();
        String permissions = loginUser.getPermission();
        if (permissions != null && !permissions.equals("")){
            //获取用户中的所有权限，此处用作示例
            List<String> perms = Arrays.asList(permissions.split(","));
            //设置当前用户权限
            info.addStringPermissions(perms);
        }

        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("拦截进入验证方法->doGetAuthenticationInfo");
        UsernamePasswordToken userToken = (UsernamePasswordToken)token;
        //查询数据库中的用户名
        User loginUser = userService.getUserByName(userToken.getUsername());
        if (loginUser == null){
            //找不到数据库中对应的用户名数据，返回null，自动抛出UnknownAccountException
            throw new UnknownAccountException();
        }
        if (loginUser.isEnable()){
            throw new LockedAccountException();
        }

        Subject currentSubject = SecurityUtils.getSubject();
        Session session = currentSubject.getSession();
        session.setAttribute("loginUser",loginUser);

        //shiro 验证密码
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(loginUser, loginUser.getPassWord(), getName());
        return simpleAuthenticationInfo;
    }
}
